<template>
  <div>
    <van-field
      v-model="telcode"
      center
      clearable
      placeholder="请输入手机验证码"
    >
      <template #button>
        <van-button @click="sendCode" :disabled="btnFlag" size="small" type="primary">{{ text }}</van-button>
      </template>
    </van-field>
    <van-button @click="step" :disabled="flag" round class="btn" block color="#ff6666">下一步</van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Field, Button, Toast } from 'vant'
import { dosendmsgcode, docheckcode } from './../../api/user'
Vue.use(NavBar)
Vue.use(Field)
Vue.use(Button)
Vue.use(Toast)
export default {
  data () {
    return {
      telcode: '',
      text: '发送验证码',
      timer: null,
      time: 5
    }
  },
  computed: {
    btnFlag () {
      return this.time > 0 && this.time < 5
    },
    flag () {
      return this.telcode === '' || this.telcode.length < 5
    }
  },
  methods: {
    step () {
      // 验证验证码
      docheckcode({
        tel: localStorage.getItem('tel'),
        telcode: this.telcode
      }).then(res => {
        if (res.data.code === '10007') {
          Toast('验证码输入错误')
        } else {
          this.$router.push('/register/step3')
        }
      })
    },
    sendCode () {
      this.timer = setInterval(() => {
        this.time--
        if (this.time === 0) {
          clearInterval(this.timer)
          this.text = '发送验证码'
          this.time = 5
        } else {
          this.text = '重新发送(' + this.time + ')'
        }
      }, 1000)
      dosendmsgcode({
        tel: localStorage.getItem('tel')
      }).then(res => {
        // 实际上验证码得手机接收，此接口直接打印出来，并没有调用真实的第三方的发送验证码
        console.log(res.data.data)
        Toast('短信验证码已发送至您的手机')
      })
    }
  },
  mounted () {
    this.sendCode()
  }
}
</script>

<style lang="stylus" scoped>
.content
  padding 30px 20px
  .btn
    margin-top 40px
</style>
